package com.netty.io.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter {

    private final ByteBuf firstMessage;

    public TimeClientHandler(){
        byte[] requestByte = "QUERY TIME ORDER".getBytes();

        firstMessage = Unpooled.buffer(requestByte.length);

        firstMessage.writeBytes(requestByte);
    }

    public void channelActive(ChannelHandlerContext ctx){
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        ByteBuf request = (ByteBuf) msg;

        byte[] byteArr = new byte[request.readableBytes()];

        request.readBytes(byteArr);

        String str = new String(byteArr, "UTF-8");

        System.out.println("Now is :" + str);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        ctx.close();
    }
}
